<template>
  <div class="vix-section">
    <u-row flex style="flex-wrap: nowrap; width: 100%">
      <u-col :span="8" style="padding-right: 16px">
        <u-tree
          :tree-data="treeData"
          default-expand-all
          @select="handleTreeSelect"
        >
          <template #title="{ node }">
            <u-tag
              v-if="node.key !== 'root'"
              class="menu-tree-tag"
              :color="
                getEnumDisplay(node.departmentType, departmentTypeOptions, {
                  value: 'value',
                  label: 'color'
                })
              "
            >
              {{ getEnumDisplay(node.departmentType, departmentTypeOptions) }}
            </u-tag>
            <span>{{ node.departmentName }}</span>
          </template>
          <template #operateBox="{ node }">
            <u-space size="mini">
              <u-link
                v-if="node.level < 2"
                type="primary"
                :underline="false"
                @click="handleAdd(node)"
              >
                <u-icon type="add-circle-outline" :size="14" />
              </u-link>
              <u-link
                v-if="node.key !== 'root'"
                type="primary"
                :underline="false"
                @click="handleEdit(node)"
              >
                <u-icon type="edit" :size="14" />
              </u-link>
              <u-pop-confirm
                v-if="node.key !== 'root'"
                title="确认删除吗?"
                @confirm="handleDelete(node)"
              >
                <u-link type="primary" :underline="false">
                  <u-icon type="delete" :size="14" />
                </u-link>
              </u-pop-confirm>
            </u-space>
          </template>
        </u-tree>
      </u-col>
      <u-col :span="16">
        <div>
          <dynamics-filter
            :setting="querySetting"
            :loading="listQuery.loading"
            button-inline
            :wrapper-width="200"
            @query="handleQuery"
          />
        </div>
        <div>
          <u-table
            :columns="columns"
            :data="listData"
            :loading="listQuery.loading"
            :border="false"
            row-key="id"
            show-pagination
            :pagination="{
              total: listQuery.total,
              current: listQuery.currentPage,
              pageSize: listQuery.pageSize,
              showSizer: true,
              showTotal: true
            }"
            @change="handleTableChange"
          >
            <template #userType="{ row }">
              {{ getEnumDisplay(row.type, roleTypeOptions) }}
            </template>
            <template #createTime="{ row }">
              {{ parseTime(row.createDate, 'YYYY-MM-DD HH:mm:ss') }}
            </template>
          </u-table>
        </div>
      </u-col>
    </u-row>
    <edit-drawer
      v-model:visible="editShow"
      :title="editTitle"
      show-submit
      :submit-loading="saveLoading"
      @submit="handleSave"
      @close="handleClose"
      @cancel="handleClose"
    >
      <dynamics-form ref="formRef" :setting="editSetting" :model="editData" />
    </edit-drawer>
  </div>
</template>

<script>
import { computed, reactive, ref } from 'vue'
import {
  DynamicsFilter,
  DynamicsForm,
  EditDrawer,
  message,
  libs,
  hooks
} from '@bairong/vix'
import config from '@/config/config'
import {
  getDepartmentListApi,
  getUserListApi,
  addDepartmentApi,
  updateDepartmentApi,
  deleteDepartmentApi
} from '@/api/author'
import { departmentTypeOptions } from '@/libs/data/enums'

const { getEnumDisplay, parseTime } = libs.conversion
const { usePageList } = hooks

export default {
  name: 'DepartmentManage',
  components: {
    DynamicsFilter,
    DynamicsForm,
    EditDrawer
  },
  setup() {
    const deptData = ref([])
    const treeData = ref([])
    // ===== deptment tree ========
    // #region
    const buildTree = () => {
      const deepBuildTree = (node, level = 2) => {
        const children = deptData.value
          .filter(x => x.superId === node.id)
          .map(x => ({ ...x, key: x.id, level }))
        node.children = children
        node.children.forEach(n => {
          deepBuildTree(n, level + 1)
        })
      }

      const lv1 = deptData.value
        .filter(x => x.superId === 0)
        .map(x => ({ ...x, key: x.id, level: 1 }))
      lv1.forEach(n => {
        deepBuildTree(n)
      })
      const children = lv1 || []
      treeData.value = [
        {
          departmentName: config.companyName,
          key: 'root',
          id: 0,
          level: 0,
          children
        }
      ]
    }

    const getDeptData = () => {
      getDepartmentListApi().then(data => {
        deptData.value = data
        buildTree()
      })
    }

    getDeptData()

    // #endregion

    // ======= getRoleType =========
    // #region
    const roleTypeOptions = ref([])

    // store.dispatch('getRoleTypeOptions').then(rst => {
    //   roleTypeOptions.value = rst;
    // });

    // #endregion

    // ======= userList ==========
    // #region

    const querySetting = ref([
      {
        name: 'key',
        label: '用户名/登录名',
        placeholder: '请输入用户名/登录名查询',
        type: 'input'
      }
    ])

    const columns = ref([
      {
        title: '姓名',
        key: 'realName'
      },
      {
        title: '登录名',
        key: 'userName'
      },
      {
        title: '用户类型',
        key: 'userType',
        slot: 'userType'
      },
      {
        title: '角色',
        key: 'roleNames'
      },
      {
        title: '创建时间',
        key: 'createTime',
        slot: 'createTime',
        minWidth: 150
      }
    ])

    const appendParams = reactive({
      departmentId: 0,
      flag: 2
    })

    const {
      listData,
      listQuery,
      getList,
      handleQuery,
      handlePageChange
    } = usePageList({
      getListApi: getUserListApi,
      getQueryParameters: DynamicsFilter.libs.getQueryParameters,
      appendParams
    })

    getList()

    const handleTableChange = pagination => {
      handlePageChange(pagination.current, pagination.pageSize)
    }

    const selectDeptid = ref()
    const handleTreeSelect = ([data]) => {
      selectDeptid.value = data.id
      appendParams.departmentId = data.id
      listQuery.currentPage = 1
      getList()
    }

    // #endregion
    // ======= deptment edit =======

    // #region
    const formRef = ref(null)
    const operateType = ref('add')
    const editShow = ref(false)
    const saveLoading = ref(false)
    const initModel = () => ({
      departmentName: '',
      departmentType: ''
    })

    const editData = ref(initModel())

    const editSetting = ref([
      {
        name: 'departmentName',
        label: '部门名称',
        placeholder: '请输入部门名称',
        type: 'input',
        rules: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          {
            pattern: /^[\u4E00-\u9FA5a-zA-Z0-9._&]{1,20}$/,
            message: '部门名称仅1-20位中文、英文、数字、符号._&',
            trigger: 'blur'
          }
        ]
      },
      {
        name: 'departmentType',
        label: '类型',
        type: 'radioGroup',
        options: departmentTypeOptions,
        disabled: ({ model }) => model.superId !== 0,
        rules: [
          {
            required: true,
            message: '请选择类型',
            trigger: 'change',
            type: 'number'
          }
        ]
      }
    ])

    const editTitle = computed(() => (operateType.value === 'add' ? '新建部门' : '编辑部门'))

    const handleAdd = data => {
      operateType.value = 'add'
      editData.value = initModel()
      editData.value.superId = data.id
      editData.value.departmentType = data.departmentType || ''
      editShow.value = true
    }

    const handleEdit = data => {
      operateType.value = 'edit'
      const { departmentName, departmentType, id } = data
      editData.value = {
        id,
        departmentName,
        departmentType
      }

      editShow.value = true
    }

    const handleClose = () => {
      formRef.value.resetFields()
      editShow.value = false
    }

    const handleSave = () => {
      formRef.value.validate().then(() => {
        const params = {
          ...editData.value
        }
        saveLoading.value = true;

        (operateType.value === 'add' ? addDepartmentApi : updateDepartmentApi)(
          params
        )
          .then(() => {
            saveLoading.value = false
            message.success('保存成功')
            handleClose()
            getDeptData()
          })
          .catch(err => {
            saveLoading.value = false
            message.error(err)
          })
      })
    }

    const handleDelete = ({ id }) => {
      deleteDepartmentApi({ id })
        .then(() => {
          message.success('删除成功')
          getDeptData()
          if (id === selectDeptid.value) {
            appendParams.departmentId = 0
            listQuery.currentPage = 1
            getList()
          }
        })
        .catch(err => {
          message.error(err)
        })
    }

    // #endregion

    return {
      treeData,
      querySetting,
      columns,
      listData,
      listQuery,
      formRef,
      editShow,
      editTitle,
      editData,
      editSetting,
      saveLoading,
      handleAdd,
      handleEdit,
      handleSave,
      handleDelete,
      handleClose,
      handleQuery,
      handleTableChange,
      handleTreeSelect,
      getEnumDisplay,
      parseTime,
      departmentTypeOptions,
      roleTypeOptions
    }
  }
  // data() {
  //   return {
  //     // 新建、保存loading
  //     saveLoading: false,
  //     // 控制新建按钮显隐
  //     addBtnShow: true
  //   };
  // },

  // methods: {
  //   // 初始化数据
  //   initModel() {
  //     return {
  //       departmentName: '',
  //       departmentType: ''
  //     };
  //   },
  //   // 新建部门事件
  //   handleAddChild(data) {
  //     this.operateType = 'add';
  //     this.editData = this.initModel();
  //     this.editData.superId = data.id;
  //     this.editData.departmentType = data.departmentType || '';
  //     // 非根下建部门，类型不能修改
  //     if (data.level !== 0) {
  //       this.editSetting.find(
  //         x => x.column === 'departmentType'
  //       ).disabled = true;
  //     } else {
  //       this.editSetting.find(
  //         x => x.column === 'departmentType'
  //       ).disabled = false;
  //     }
  //     this.editShow = true;
  //   },
  //   // 抽屉关闭事件
  //   handleClose() {
  //     this.$refs.form.resetFields();
  //     this.editShow = false;
  //   },
  //   /**
  //    * @description: 列表编辑事件
  //    * @param : row -> 编辑对象信息
  //    * @return:
  //    */
  //   handleEdit(row) {
  //     this.operateType = 'edit';
  //     const { departmentName, departmentType, id } = row;
  //     this.editData = {
  //       id,
  //       departmentName,
  //       departmentType
  //     };
  //     this.editSetting.find(x => x.column === 'departmentType').disabled = true;
  //     this.editShow = true;
  //   },
  //   // 保存事件
  //   handleSave() {
  //     this.$refs.form.validate(valid => {
  //       if (valid) {
  //         const params = {
  //           ...this.editData
  //         };
  //         this.saveLoading = true;
  //         const submitSave =
  //           this.operateType === 'add' ? addDepartmentApi : updateDepartmentApi;
  //         submitSave(params)
  //           .then(() => {
  //             this.editShow = false;
  //             this.saveLoading = false;
  //             this.$refs.form.resetFields();
  //             this.$Message.success('保存成功');
  //             this.getData();
  //           })
  //           .catch(err => {
  //             this.saveLoading = false;
  //             this.$Message.error(err);
  //           });
  //       }
  //     });
  //   },
  //   /**
  //    * @description: 列表删除事件
  //    * @param : id -> 当前列表数据id
  //    * @return:
  //    */
  //   handleDelete({ id }) {
  //     deleteDepartmentApi({ id })
  //       .then(() => {
  //         this.$Message.success('删除成功');
  //         this.getData(id === this.selectDetpId);
  //       })
  //       .catch(err => {
  //         this.$Message.error(err);
  //       });
  //   }
  // }
}
</script>
